# -*- coding: utf-8 -*-

from Products.Archetypes.public import *
from Products.CMFCore.CMFCorePermissions import View
from AccessControl import ClassSecurityInfo

META_TYPE = 'Concept'

conceptSchema = Schema((
    StringField('title',
        required=1,
        searchable=1,
        accessor='Title',
        widget=StringWidget(
            label='Preferred label',
            description='The preferred lexical label for a resource, in a given language.'
        ),
    ),
    TextField('definition',
        searchable=1,
        widget=TextAreaWidget(
            label='Definition',
            description='A statement or formal explanation of the meaning of a concept.',
        ),
    ),
    TextField('scopeNote',
        searchable=1,
        widget=TextAreaWidget(
            label='Scope note',
            description='A note that helps to clarify the meaning and usage of a concept.',
        ),
    ),
    LinesField('altLabels',
        searchable=1,
        widget=LinesWidget(
            label='Alternative labels',
            description='Alternative lexical labels for a resource (type one per line).',
        ),
    ),
    ReferenceField('related',
        widget=ReferenceWidget(
            label='Related to',
            description='A concept with which there is an associative semantic relationship.',
        ),
        allowed_types=(META_TYPE,),
        multiValued=1,
        relationship='associação',
    ),
))

class Concept(BaseFolder):
    '''
    Thesaurus concept
    '''
    
    baseSchema = BaseFolderSchema.copy()
    baseSchema['id'].widget.visible = {'edit':'hidden','view':'hidden',}
    
    #del baseSchema['title']

    schema = baseSchema + conceptSchema
    

    actions = (
        {   'id': 'view',
            'name': 'View',
            'action': 'string:${object_url}/concept_view',
            'permissions': (View,)
        },
        {   'id': 'listing',
            'name': 'Listagem',
            'action': 'string:${object_url}/alpha_listing',
            'permissions': (View,)
        },
        {   'id': 'tree_view',
            'name': 'Árvore',
            'action': 'string:${object_url}/tree_view',
            'permissions': (View,)
        },
    )
    
    filter_content_types = 1
    allowed_content_types = [META_TYPE]
    content_icon = 'tesauro_icon.gif'
    
    security = ClassSecurityInfo()

    security.declareProtected(View, 'getBroaderTerm')
    def getBroaderTerm(self):
        # XXX: how to obtain the container w/o using acquisition?
        if self.aq_parent.meta_type == META_TYPE:
            return self.aq_parent
        else:
            return None
    
    security.declareProtected(View, 'listNarrower')
    def listNarrower(self):
        ''' list immediate narrower terms '''
        list = [(concept.Title(), concept) for concept in self.contentValues(META_TYPE)]
        list.sort()
        return [concept for title, concept in list]
        
    security.declareProtected(View, 'getRootTerm')
    def getRootTerm(self):
        '''get the topmost term'''
        here = self
        while 1:
            parent = here.getBroaderTerm()
            if parent is None:
                return self
            elif parent.meta_type != META_TYPE:
                return here
            here = parent
        
    security.declareProtected(View, 'listAllTerms')
    def listAllTerms(self): 
        '''list all narrower terms from the top'''
        return self.getRootTerm().listAllNarrowerTerms()

    security.declareProtected(View, 'listAllNarrowerTerms')
    def listAllNarrowerTerms(self):    
        ''' list all terms below this one '''
        res = self.portal_catalog(Type=META_TYPE,path='/'.join(self.getPhysicalPath()))
        res = [(r.Title, r.getObject()) for r in res]
        listing = []
        for prefLabel, term in res:
            listing.append((prefLabel.upper(), 
                {'label':prefLabel,'term':term,'url':term.absolute_url()}))
            for altLabel in term.getAltLabels():
                listing.append((altLabel.upper(), 
                    {'label':altLabel,'use':prefLabel,'url':term.absolute_url()}))
        listing.sort()
        return [dic for label, dic in listing]
                
registerType(Concept)


